<?php 
/***
 * 分类管理控制器
 */
class CategoryController extends AuthController{
	private $model;
	public function __init(){
		parent::__init();
		$this->model = K('category');
	}
	
	/**
	 * 加载首页
	 */
	public function index(){
		//分配分类数据
		$cate = $this->model->order("csort ASC")->all();
		$data = Data::tree($cate, 'cname','cid','pid');
		$this->assign('data',$data);
		$this->display();
		
	}
	
	/**
	 * 添加分类
	 */
	public function add(){
		if(IS_POST){
			if(!$this->model->addCate()) $this->error($this->model->error);
			$this->success('添加成功',U('Admin/Category/add'));
		}
		
		$this->display();
	}
	
	/**
	 * 添加子分类 
	 */
	public function addSon(){
		//获得类型数据,并分配到模板中
		$type = K('Type')->all();
		$this->assign('type',$type);
		//获取所属分类
		$cid = Q('get.cid',0,'intval');
		$cname = $this->model->where("cid={$cid}")->find();
		$this->assign('cname',$cname);
		if(IS_POST){
			if(!$this->model->addSon()) $this->error($this->model->error);
			$this->success('添加成功');
		}

		$this->display();
	}
	
	
	/***
	 * 编辑
	 */
	public function edit(){
		//获取cid
		$cid = Q('get.cid',0,'intval');
		$oldData = $this->model->where("cid={$cid}")->find();
		$this->assign('oldData',$oldData);
		//获取类型
		$type = K('Type')->all();
		$this->assign('type',$type);
		//处理所属分类
		$sonCid = $this->model->getSon($this->model->all(), $cid);
		$sonCid[] = $cid;
		$data = $this->model->where("cid NOT IN(" . implode(',', $sonCid) . ")")->all();
		$data = Data::tree($data, 'cname','cid','pid');
		$this->assign('data',$data);
		//post提交数据
		if(IS_POST){
			if(!$this->model->edit($cid)) $this->error($this->model->error);
			$this->success('修改成功',U('Category/index'));
		}
		$this->display();
	}
	
	
	
	
	
	/**
	 * 删除分类
	 */
	public function delete(){
		$cid = Q('get.cid',0,'intval');
		$isSon = $this->model->where("pid={$cid}")->all();
		if($isSon){
			$this->error('有子分类请先删除子分类');
		}else{
			$this->model->where("cid={$cid}")->delete();
			$this->success('删除成功',U('index'));
		}
		
	}
	
	/**
	 * ajax处理列表的伸展：获取点击类别的 子集
	 */
	public function ajaxSoncid(){
		$cid = Q("post.cid");
		$sonCid = $this->model->getSon($this->model->all(),$cid);
		echo json_encode($sonCid);die;
	}
	
	
	

	
	
	
	
	
	
	
	
}























 ?>